package com.hhz.springcloud.controller;

import com.hhz.springcloud.service.PaymentHystrixService;
import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * @Author Rem
 * @Date 2020-03-12
 * @Version 1.0
 */

@RestController
@RequestMapping("/consumer")
@DefaultProperties(defaultFallback = "paymentGlobalFallbackmethod")
public class OrderHystrixController {

    @Resource
    private PaymentHystrixService paymentHystrixService;

    /**
     * 测试超时压测 导致服务器占满 正常访问也会导致超时发生
     * java.util.concurrent.TimeoutException: null
     * http://localhost/consumer/payment/hystrix/ok/2
     *
     * @param id
     * @return
     */
    @GetMapping("/payment/hystrix/ok/{id}")
    public String paymentInfo_OK(@PathVariable("id") Long id) {
        return paymentHystrixService.paymentInfo_OK(id);
    }


    /**
     * 客户端设置最大时长1.5s访问服务端 超时或者报错进入兜底方法
     *
     * @param id
     * @return
     */
    @GetMapping("/payment/hystrix/timeout/{id}")
    /*@HystrixCommand(fallbackMethod = "payment_TimeOutFallbackMethod", commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "1500")
    })*/
    @HystrixCommand
    public String paymentInfo_Timeout(@PathVariable("id") Long id) {
        //int a = 10 / 0;
        return paymentHystrixService.paymentInfo_Timeout(id);
    }

    /**
     * 兜底方法导致代码膨胀
     * 处理方法和主业务逻辑混合在一起
     *
     * @param id
     * @return
     */
    public String payment_TimeOutFallbackMethod(@PathVariable("id") Long id) {
        return "我是80消费方法 对方繁忙或自己运行出错~~~";
    }

    /**
     * hystrix服务降级
     * 全类兜底方法(在本class中有效)
     * 1.添加方法
     * 2.类上添加注解@DefaultProperties
     * 3.在方法上添加@HystrixCommand 表示会进入处理的方法,级别比全局高 不加注解表示默认全局处理方法
     */
    private String paymentGlobalFallbackmethod() {
        return "全类异常处理信息,请稍后重试~~";
    }


}
